package com.killer.order.service.impl;

import com.killer.common.util.CloneUtil;
import com.killer.goods.dto.SkuChangeDTO;
import com.killer.goods.feign.SkuClient;
import com.killer.leaf.feign.SnowFlakeClient;
import com.killer.order.dto.OrderItemDTO;
import com.killer.order.entity.Order;
import com.killer.order.entity.OrderItem;
import com.killer.order.mapper.OrderMapper;
import com.killer.order.service.ICartService;
import com.killer.order.service.IOrderItemService;
import com.killer.order.service.IOrderService;
import com.killer.db.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author killer
 * @since 2021-11-06
 */
@Service
public class OrderServiceImpl extends BaseServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private ICartService cartService;
    @Autowired
    private SnowFlakeClient snowFlakeClient;
    @Autowired
    private IOrderItemService orderItemService;
    @Autowired
    private SkuClient skuClient;

    /**
     * 添加订单
     * @param order
     */
    @Transactional
    public void add(Order order) {
        //获取购物车列表
        Map<String, Object> cartMap = cartService.list(order.getUserId());
        //获取订单条目
        List<OrderItemDTO> orderItemList = (List<OrderItemDTO>) cartMap.get("orderItemList");
        //设置订单id，用分布式id
        order.setId(snowFlakeClient.getId().getData());
        //统计计算
        int totalNum = 0;
        int totalPrice = 0;
        List<SkuChangeDTO> dtos = new ArrayList<>();
        for (OrderItemDTO orderItemDTO : orderItemList) {
            //只统计勾选的
            if (orderItemDTO.getChecked()) {
                totalNum += orderItemDTO.getNum();
                totalPrice += orderItemDTO.getMoney();
                //保存订单明细
                OrderItem orderItem = CloneUtil.convert(orderItemDTO, OrderItem.class);
                orderItemService.save(orderItem);
                //删除购物车信息
                cartService.delete(order.getUserId(), orderItemDTO.getSkuId());
                //保存Sku变更信息
                dtos.add(new SkuChangeDTO(orderItemDTO.getSkuId(), orderItemDTO.getNum()));
            }
        }
        order.setTotalNum(totalNum);
        order.setTotalMoney(totalPrice);
        order.setPayMoney(totalPrice);
        order.setSourceType(1);//订单来源
        order.setBuyerRate(false);//评价状态
        order.setOrderStatus(0);//订单状态
        order.setPayStatus(0);//支付状态
        order.setConsignStatus(0); //未发货
        //保存订单
        super.save(order);
        //调用商品微服务扣减库存及其销量变更

        //调用用户微服务增加积分

        //将订单编号发送到order-create topic中

    }


}
